package com.windy.spring.dao.jpa;

import java.lang.reflect.ParameterizedType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.windy.spring.dao.Dao;



public abstract class JpaDao <E, K> implements Dao<E, K> {
	protected Class<E> entityClass;
	
	private static final Logger logger = LoggerFactory.getLogger(JpaDao.class);
	 
	@PersistenceContext(type=PersistenceContextType.EXTENDED)
	protected EntityManager entityManager;
 
	public JpaDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
		logger.info(this.entityClass.toString());
	}
 
	@Transactional
	public void persist(E entity) { entityManager.persist(entity); }
 
	public void remove(E entity) { entityManager.remove(entity); }
 
	public E findById(K id) { return entityManager.find(entityClass, id); }
}
